<?php

namespace app\controllers;
use yii\web\Controller;
use Yii;
use app\models\comment;
use app\models\content;

class CommentController extends Controller{
	public $enableCsrfValidation = false;
	//信息发布
	public function actionGet(){
		$model = new comment();
		$content = new content();
		if(Yii::$app->request->isPost){
			$postData = Yii::$app->request->bodyParams;
			$Content_ID = $postData['id'];
		    //获取内容
		    $c_arr = $content->find()->select('*')->where('State = :State', [":State"=>'1'])->andwhere('Content_ID = :Content_ID', [":Content_ID"=>$Content_ID])->asArray()->all();
		    if(!empty($c_arr)){
		    	//获取评论
	            $p_arr = $model->find()->select('*')->where('State = :State', [":State"=>'1'])->andwhere('View_ID = :Content_ID', [":Content_ID"=>$Content_ID])->orderby('Comment_ID desc')->asArray()->all();
	            $p_num = $model->find()->select('count(*)')->where('State = :State', [":State"=>'1'])->andwhere('View_ID = :Content_ID', [":Content_ID"=>$Content_ID])->asArray()->all();
	            $p_num = (int)$p_num[0]['count(*)'];
	            if($p_num == 0){
	            	$data = array('Content' => $c_arr, 'Count_P' => $p_num);
	            	echo json_encode(array('error' => 0, 'message' => 'success', 'data'=>$data));
	            }else{
	            	$modcontent = array('Comment' => $p_num);
                    $content->mod($Content_ID, $modcontent);
                    $data = array('Content' => $c_arr, 'Comment' => $p_arr, 'Count_P' => $p_num);
                    echo json_encode(array('error' => 0, 'message' => 'success', 'data' => $data));
	            }
		    }else{
		    	$data = array('Content' => '没有这段内容');
	        	echo json_encode(array('error' => 1, 'message' => 'fail', 'data' => $data));
		    }		        	
        }    
	}


	//信息接收&数据库输入
	public function actionPublish(){
		$model = new comment();
		$content = new content();
        if( Yii::$app->request->isPost ){
         	//输入数据
         	$postData = Yii::$app->request->post();
            $Content_ID = $postData['id'];
            $checkcontent = $content->find()->select('*')->where('State = :State', [":State"=>'1'])->andwhere('Content_ID = :Content_ID', [":Content_ID"=>$Content_ID])->asArray()->all();
            if(!empty($checkcontent)){
        	    $result = $model->add($postData);
        	    if( $result == 0 ){
        		    $data = array('Content' => '提交数据成功');
        		    echo json_encode(array('error' => 0, 'message' => 'success', 'data' => $data));
        	    }else{
        		    $data = array('content' => '提交数据失败,请@留言,联系公众号~', 'Content' => $result);
                    echo json_encode(array('error' => 1, 'message' =>fail, 'data' => $data));
        	    }
        	}else{
        		$data = array('Content' => '错误ContentID');
        		echo json_encode(array('error' => -1, 'message' => fail, 'data' => $data));
        	}
        }
    }        




}